package net.stogi.unicore.beyond.io.input.datefield;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.springframework.format.annotation.DateTimeFormat;

import net.stogi.common.api.exception.Messages;
import net.stogi.unicore.beyond.api.model.PropertyValue;
import net.stogi.unicore.beyond.io.input.core.InputValidator;
import net.stogi.unicore.beyond.io.input.core.PropertyUtils;

public class DateInputValidator implements InputValidator {

	@Override
	public boolean validate(String inputName, String inputValue, Map<String, PropertyValue> properties, Messages messages) {
		boolean valid = true;

		// Not empty.
		{
			boolean empty = PropertyUtils.asBoolean(properties.get("empty"));
			if (!empty && inputValue == null) {
				messages.error(inputName, "Field can not be empty");
				return false;
			}
		}
		DateFormat format = DateFormat.getDateTimeInstance();
		if (inputValue != null) {
			Date value = null;
			try {
				value = format.parse(inputValue);
			}
			catch (ParseException e) {
				messages.error(inputName, "Problem with date parsing");
				return false;
			}
			// First value.
			{
				Date first = PropertyUtils.asDate(properties.get("first"), format);
				if (first != null && value.before(first)) {
					messages.error(inputName, String.format("Field value can not be before %1$t date", first));
					valid = false;
				}
			}
			// Last value.
			{
				Date last = PropertyUtils.asDate(properties.get("last"), format);
				if (last != null && value.after(last)) {
					messages.error(inputName, String.format("Field value can not be after %1$t date", last));
					valid = false;
				}
			}
		}

		return valid;
	}
}
